<template>
  <div class="subandentry">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="back" @click="goBack">←返回</div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        class="demo-ruleForm"
        status-icon
      >
        <div class="title">故障信息</div>
        <el-row class="row">
          <el-col :span="6">
            <el-form-item label="维修设备" prop="deviceId">
              <el-select
                v-model="ruleForm.deviceId"
                filterable
                placeholder="选择维修设备"
                style="width: 100%"
                @change="deviceChange"
              >
                <el-option
                  v-for="item in deviceList"
                  :label="item.deviceName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="故障类型" prop="failureCategoryId">
              <el-cascader
                :show-all-levels="false"
                v-model="ruleForm.failureCategoryId"
                placeholder="选择故障类型"
                :props="cascaderProps"
                :options="failureList"
                style="width: 100%"
                @change="failureChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="故障现象" prop="failurePhenomenonId">
              <el-select
                v-model="ruleForm.failurePhenomenonId"
                placeholder="选择故障现象"
                style="width: 100%"
                @change="phenomenonChange"
              >
                <el-option
                  v-for="item in phenomenonList"
                  :label="item.failureName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item label="解决方案" prop="solution">
              <el-input
                v-model="ruleForm.solution"
                type="textarea"
                placeholder="解决方案"
                maxlength="128"
                show-word-limit
                rows="4"
              />
              <div>
                <span class="tips"
                  >故障类型、现象及解决方案，可在【设备维修管理-故障项管理】中配置</span
                >
                <span class="sets" @click="goSetting">去设置</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="故障等级" prop="failureLevelId">
              <el-cascader
                :show-all-levels="false"
                v-model="ruleForm.failureLevelId"
                @change="levelChange"
                :props="cascaderPropsLevel"
                :options="failureLevels"
                style="width: 100%"
                placeholder="选择故障等级"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item label="故障描述" prop="description">
              <el-input
                v-model="ruleForm.description"
                type="textarea"
                placeholder="故障描述"
                maxlength="128"
                show-word-limit
                rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <div class="title">维修信息</div>
        <el-row class="row">
          <el-col :span="6">
            <el-form-item label="维修厂家" prop="repairFactory">
              <el-select
                v-model="ruleForm.repairFactory"
                placeholder="选择维修厂家"
                style="width: 75%"
              >
                <el-option
                  v-for="item in gyOptions"
                  :key="item.id"
                  :label="item.factoryName"
                  :value="item.factoryName"
                />
              </el-select>
              <el-button
                type="primary"
                @click="addSupplier()"
                style="width: 25%"
              >
                添加厂家
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="维修人员" prop="repairUserName">
              <el-input
                v-model="ruleForm.repairUserName"
                placeholder="输入维修人员名称"
                maxlength="8"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="维修费用" prop="outsourceFee">
              <el-input
                v-model="ruleForm.outsourceFee"
                placeholder="输入维修费用"
                style="width: 90%"
                type="text"
                maxlength="8"
                show-word-limit
                onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g,'$1')"
              />元
              <div style="font-size: 12px">
                提示：内部使用备件费用，不计算在维修费用中
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="6">
            <el-form-item label="维修开始时间" prop="startTime">
              <el-date-picker
                v-model="ruleForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                size="default"
                value-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="维修结束时间" prop="endTime">
              <el-date-picker
                v-model="ruleForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                size="default"
                value-format="YYYY-MM-DD HH:mm"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="12">
            <el-form-item label="维修内容" prop="content">
              <el-input
                v-model="ruleForm.content"
                type="textarea"
                placeholder="维修内容"
                maxlength="128"
                show-word-limit
                rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="维修照片" porp="repairImg">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo2"
            :action="`${proxy.$http}/user/upload/uploadFile`"
            :http-request="(resp: any) => { return handleUpload(resp, 15) }"
            limit="9"
            :headers="headers"
            accept=".png,.jpg,.jpeg,.mp4"
            :show-file-list="false"
            multiple
            :on-exceed="(resp: any) => { return fileExceedUpload() }"
            :before-upload="(resp: any) => { return fileBeforeUpload(resp, 15) }"
            :before-remove="uploadRemove"
            :on-error="(resp: any) => { return fileError(resp, 15) }"
          >
            <el-button type="primary">上传图片或视频</el-button>
          </el-upload>
          <div class="tips" style="margin: auto auto 0px 5px">
            可传视频或图片，最多9个
          </div>
        </el-form-item>
        <el-form-item>
          <div style="display: flex">
            <div v-for="(item, index) in filePictrueList">
              <el-image
                style="width: 94px; height: 84px; padding: 0 5px"
                :src="item"
                :zoom-rate="1.2"
                v-if="
                  item.substring(item.indexOf('?') - 3, item.indexOf('?')) ==
                    'jpg' ||
                  item.substring(item.indexOf('?') - 3, item.indexOf('?')) ==
                    'png' ||
                  item.substring(item.indexOf('?') - 3, item.indexOf('?')) ==
                    'peg'
                "
                :preview-src-list="filePictrueList"
                :initial-index="index"
                fit="cover"
              />
              <div style="text-align: center">
                <el-button type="text" @click="deletePic(item, index, 1)"
                  >删除</el-button
                >
              </div>
            </div>
            <div v-for="(item, index) in fileVedioList">
              <video
                :src="item"
                class="avatar"
                controls="controls"
                style="width: 94px; height: 84px; padding: 0 5px"
                @play="handleFullScreen"
              ></video>
              <div style="text-align: center">
                <el-button type="text" @click="deletePic(item, index, 2)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="附件" porp="repairImg" style="width: 100%">
          <el-upload
            v-model:file-list="fileList3"
            class="upload-demo"
            :headers="headers"
            :action="`${proxy.$http}/user/upload/uploadFile`"
            limit="10"
            multiple
            :http-request="(resp: any) => { return handleUpload3(resp, 15) }"
            :before-upload="(resp: any) => { return fileBeforeUpload2(resp, 15) }"
            :on-exceed="(resp: any) => { return fileExceedUpload2() }"
            :on-error="(resp: any) => { return fileError(resp, 15) }"
            :before-remove="uploadRemove3"
          >
            <el-button type="primary">
              <svg
                t="1679398463697"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="3392"
                width="20"
                height="20"
              >
                <path
                  d="M122.88 512s0 4.096-4.096 4.096v16.384s0 4.096 4.096 4.096l4.096 4.096 4.096 4.096s4.096 0 4.096 4.096h16.384s4.096 0 4.096-4.096l4.096-4.096 380.928-380.928c12.288-12.288 24.576-20.48 36.864-24.576 12.288-4.096 28.672-8.192 45.056-8.192 16.384 0 28.672 4.096 45.056 8.192 16.384 4.096 28.672 12.288 36.864 24.576 12.288 12.288 20.48 24.576 24.576 36.864 4.096 12.288 8.192 28.672 8.192 45.056 0 16.384-4.096 28.672-8.192 45.056-4.096 16.384-12.288 28.672-24.576 36.864L438.272 614.4l-4.096 4.096s0 4.096-4.096 4.096v16.384s0 4.096 4.096 4.096l4.096 4.096 4.096 4.096s4.096 0 4.096 4.096h16.384s4.096 0 4.096-4.096l4.096-4.096L749.568 368.64c16.384-16.384 28.672-36.864 36.864-57.344 8.192-20.48 12.288-45.056 12.288-69.632s8.192-36.864 0-57.344c-8.192-20.48-20.48-40.96-36.864-57.344s-36.864-28.672-57.344-36.864-45.056-12.288-69.632-12.288c-24.576 0-45.056 4.096-69.632 12.288-20.48 8.192-40.96 20.48-57.344 36.864l-380.928 380.928c-4.096 0-4.096 4.096-4.096 4.096z"
                  fill="#ffffff"
                  p-id="3393"
                ></path>
                <path
                  d="M401.408 847.872c-12.288 4.096-28.672 8.192-45.056 8.192-16.384 0-28.672-4.096-45.056-8.192-12.288-8.192-24.576-16.384-36.864-28.672-12.288-12.288-20.48-24.576-24.576-36.864-4.096-12.288-8.192-28.672-8.192-45.056 0-16.384 4.096-28.672 8.192-45.056 4.096-16.384 12.288-28.672 24.576-36.864l311.296-311.296 4.096-4.096s0-4.096 4.096-4.096v-4.096V327.68v-4.096-4.096s0-4.096-4.096-4.096l-4.096-4.096-4.096-4.096s-4.096 0-4.096-4.096H573.44h-4.096-4.096-4.096s-4.096 0-4.096 4.096l-4.096 4.096L229.376 614.4c-16.384 16.384-28.672 36.864-36.864 57.344-8.192 20.48-12.288 45.056-12.288 69.632 0 24.576 4.096 45.056 12.288 69.632 8.192 20.48 20.48 40.96 36.864 57.344 16.384 12.288 36.864 24.576 57.344 32.768 20.48 8.192 45.056 12.288 69.632 12.288s45.056-4.096 69.632-12.288c20.48-8.192 40.96-20.48 57.344-36.864l380.928-380.928 4.096-4.096s0-4.096 4.096-4.096v-4.096-4.096-4.096-4.096s0-4.096-4.096-4.096l-4.096-4.096-4.096-4.096s-4.096 0-4.096-4.096h-4.096-4.096-4.096-4.096s-4.096 0-4.096 4.096l-4.096 4.096-393.216 368.64c-12.288 12.288-24.576 20.48-36.864 28.672z"
                  fill="#ffffff"
                  p-id="3394"
                ></path>
              </svg>
              上传附件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                最多上传10个附件，每个附件不得超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-divider />
        <div class="title">备件申请信息</div>
        <el-row class="row">
          <el-col :span="18">
            <el-form-item
              :label="tableData.length > 0 ? '备件申请列表' : ''"
              prop="region"
            >
              <div
                :style="
                  tableData.length > 0 ? ' width: 100%; text-align: end' : ''
                "
              >
                <el-button type="primary" plain @click="addSpare()"
                  >添加备件</el-button
                >
                <el-button
                  type="primary"
                  @click="submitApply()"
                  v-if="tableData.length > 0"
                >
                  提交申请
                </el-button>
              </div>
              <el-table
                :data="tableData"
                style="width: 100%; margin-top: 10px"
                :header-cell-style="{
                  background: '#E0E0E0',
                  color: '#2B2B2B',
                  fontWeight: 500
                }"
                v-if="tableData.length > 0"
              >
                <el-table-column prop="partNum" label="备件编号" width="180" />
                <el-table-column prop="partName" label="备件名称" width="180" />
                <el-table-column prop="partTypeName" label="备件类型" />
                <el-table-column prop="totalAmount" label="申请数量" />
                <el-table-column prop="approveStatus" label="申请状态">
                  <template #default="scope">
                    <div v-if="scope.row.approveStatus != 2">
                      {{
                        scope.row.approveStatus == 0
                          ? '待提交'
                          : scope.row.approveStatus == 1
                          ? '待审核'
                          : scope.row.approveStatus == 3
                          ? '审核通过'
                          : ''
                      }}
                    </div>
                    <div v-else>
                      <span>不通过</span>
                      <el-popover
                        placement="top-start"
                        title="原因"
                        :width="200"
                        trigger="hover"
                        :content="scope.row.reason"
                      >
                        <template #reference>
                          <svg
                            t="1681107624752"
                            class="icon"
                            viewBox="0 0 1024 1024"
                            version="1.1"
                            xmlns="http://www.w3.org/2000/svg"
                            p-id="3558"
                            width="20"
                            height="20"
                          >
                            <path
                              d="M976.738462 704.984615c27.569231-63.015385 39.384615-129.969231 39.384615-196.923077s-11.815385-133.907692-39.384615-196.923076S913.723077 196.923077 866.461538 149.661538c-47.261538-47.261538-102.4-82.707692-161.476923-110.276923-63.015385-27.569231-129.969231-39.384615-196.923077-39.384615s-133.907692 11.815385-196.923076 39.384615S196.923077 102.4 149.661538 149.661538 66.953846 248.123077 39.384615 311.138462c-27.569231 63.015385-39.384615 129.969231-39.384615 196.923076s11.815385 133.907692 39.384615 196.923077c27.569231 59.076923 63.015385 114.215385 110.276923 161.476923 47.261538 47.261538 102.4 82.707692 161.476924 110.276924 63.015385 27.569231 129.969231 39.384615 196.923076 39.384615s133.907692-11.815385 196.923077-39.384615c59.076923-27.569231 114.215385-63.015385 161.476923-110.276924 47.261538-47.261538 82.707692-98.461538 110.276924-161.476923z m-31.507693-196.923077c0 59.076923-11.815385 114.215385-35.446154 169.353847-23.630769 51.2-55.138462 98.461538-94.523077 137.846153s-86.646154 70.892308-137.846153 94.523077c-55.138462 23.630769-110.276923 35.446154-169.353847 35.446154s-114.215385-11.815385-169.353846-35.446154c-51.2-23.630769-98.461538-55.138462-137.846154-94.523077s-70.892308-86.646154-94.523076-137.846153c-23.630769-55.138462-35.446154-110.276923-35.446154-169.353847s11.815385-114.215385 35.446154-169.353846C126.030769 283.569231 157.538462 240.246154 200.861538 196.923077c39.384615-39.384615 86.646154-70.892308 137.846154-94.523077 55.138462-23.630769 110.276923-35.446154 169.353846-35.446154s114.215385 11.815385 169.353847 35.446154c55.138462 23.630769 98.461538 55.138462 141.784615 94.523077 39.384615 39.384615 70.892308 86.646154 94.523077 137.846154 19.692308 59.076923 31.507692 114.215385 31.507692 173.292307z"
                              fill="#FA4016FF"
                              p-id="3559"
                            ></path>
                            <path
                              d="M508.061538 153.6c-47.261538 0-90.584615 39.384615-90.584615 90.584615s39.384615 90.584615 90.584615 90.584616 90.584615-39.384615 90.584616-90.584616-43.323077-90.584615-90.584616-90.584615zM464.738462 823.138462c3.938462 7.876923 3.938462 11.815385 11.815384 15.753846 3.938462 3.938462 7.876923 7.876923 15.753846 11.815384 7.876923 3.938462 11.815385 3.938462 19.692308 3.938462h7.876923c3.938462 0 7.876923 0 7.876923-3.938462 3.938462 0 3.938462-3.938462 7.876923-3.938461 3.938462-3.938462 3.938462-3.938462 7.876923-3.938462 0-3.938462 3.938462-3.938462 3.938462-7.876923s3.938462-3.938462 3.938461-7.876923 3.938462-3.938462 3.938462-7.876923v-7.876923h-47.261539 47.261539v-354.461539-7.876923c0-3.938462 0-7.876923-3.938462-7.876923 0-3.938462-3.938462-3.938462-3.938461-7.876923s-3.938462-3.938462-3.938462-7.876923c-3.938462 0-3.938462-3.938462-7.876923-3.938461s-3.938462-3.938462-7.876923-3.938462-3.938462-3.938462-7.876923-3.938461H512h-7.876923c-3.938462 0-7.876923 0-7.876923 3.938461-3.938462 0-3.938462 3.938462-7.876923 3.938462-3.938462 3.938462-3.938462 3.938462-7.876923 3.938461 0 3.938462-3.938462 3.938462-3.938462 7.876923s-3.938462 3.938462-3.938461 7.876923-3.938462 7.876923-3.938462 7.876923v7.876923h47.261539-47.261539v354.461539c-7.876923 0-7.876923 3.938462-3.938461 11.815385z"
                              fill="#FA4016FF"
                              p-id="3560"
                            ></path>
                          </svg>
                        </template>
                      </el-popover>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="80"
                  v-if="tableData.length > 0"
                >
                  <template #default="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="deletePart(scope.row.id)"
                      v-if="scope.row.approveStatus == 0"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item
              label="备件审核人"
              :prop="tableData.length == 0 ? '' : 'dealUserId'"
              v-if="tableData.length > 0"
            >
              <el-select
                v-model="ruleForm.dealUserId"
                filterable
                placeholder="可搜索姓名/下拉选择仓库负责人"
                @change="dealUserChange"
                style="width: 350px"
              >
                <el-option
                  v-for="item in shOptions"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />
        <div class="title">验证信息</div>
        <el-form-item label="验证人" prop="verifyUserId">
          <el-select
            v-model="ruleForm.verifyUserId"
            filterable
            placeholder="可搜索姓名/下拉选择验证人"
            style="width: 350px"
            @change="verifyUserChange"
          >
            <el-option
              v-for="item in yzOptions"
              :key="item.id"
              :label="item.realName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm(ruleFormRef, 'repairOrder')"
            >保存当前内容</el-button
          >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交验证
          </el-button>
        </el-form-item>
      </el-form>
      <PurveyorDialog
        :dialogVisible="dialogVisible"
        :dialogForm="dialogForm"
        @cancel="cancelSupplier"
        @submit="submitSupplier"
      >
      </PurveyorDialog>
      <SpareApply
        :spareDialog="spareDialog"
        :spareType="spareType"
        @saCancel="saCancel"
        @saSubmit="saSubmit"
      >
      </SpareApply>
      <!-- <el-dialog v-model="dialogImgVisible" width="35%">
                <img w-full :src="dialogImageUrl" alt="" style="width:100%;" />
            </el-dialog> -->
    </el-card>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  defineAsyncComponent,
  getCurrentInstance,
  onMounted,
  watch
} from 'vue'
import routes, { router } from '/@/router'
import { useRoute } from 'vue-router'
import {
  ElLoading,
  ElMessage,
  ElMessageBox,
  FormInstance,
  FormRules,
  UploadFile,
  UploadFiles,
  UploadProps,
  UploadUserFile
} from 'element-plus'
import {
  dictionaryList,
  getDirectorListApi,
  uploadFileApi
} from '/@/api/publicApi'
import {
  addRepairPartApplyApi,
  getDeviceListApi,
  getFailureCategoryApi,
  updateRepairApi,
  getFailurePhenomenonApi,
  addOutsourceRepairApi,
  repairDetailByOrderNumApi,
  deletePartApplyDetailApi,
  submitVerifyApi
} from '/@/api/repair'
import { getPurveyorList } from '/@/api/assets'
import { Session } from '/@/utils/storage'
import { verifiyNumberInteger } from '/@/utils/toolsValidate'
const { proxy } = getCurrentInstance() as any
const SpareApply = defineAsyncComponent(
  () => import('./components/SpareApply.vue')
)
const PurveyorDialog = defineAsyncComponent(
  () => import('../assets/components/PurveyorDialog.vue')
)
const goBack = () => {
  routes.push({
    name: 'repairOrder'
  })
}
const cascaderProps = {
  expandTrigger: 'click' as const,
  value: 'id',
  label: 'failureName',
  emitPath: false
}
const cascaderPropsLevel = {
  expandTrigger: 'click' as const,
  value: 'id',
  label: 'configValue',
  emitPath: false
}
const route = useRoute()
const id = ref(JSON.parse(JSON.stringify(route.query.id)))
const wxId = ref(JSON.parse(JSON.stringify(route.query.wxId)))
const change = ref(
  route.query.change ? JSON.parse(JSON.stringify(route.query.change)) : ''
)

const goWhere = ref('')
const ruleFormRef = ref<FormInstance>()
const tableData = ref<any>([])
const ruleForm = ref({
  deviceId: '',
  failureCategoryId: '',
  failureCategory: '',
  failurePhenomenonId: '',
  failurePhenomenon: '',
  solution: '',
  failureLevelId: '',
  failureLevel: '',
  description: '',
  repairFactory: '',
  repairUserName: '',
  outsourceFee: '',
  content: '',
  startTime: '',
  endTime: '',
  dealUserId: '',
  dealUserName: '',
  repairPictures: '',
  verifyUserId: '',
  verifyUserName: '',
  fileNames: '',
  fileUrls: '',
  fileSizes: '',
  repairOrderNum: '',
  repairId: '',
  repairStatus: '',
  source: ''
})

const validatorTime = (rules: any, value: any, callback: any) => {
  if (
    Date.parse(ruleForm.value.startTime) > Date.parse(value) ||
    Date.parse(ruleForm.value.startTime) == Date.parse(value)
  ) {
    callback(new Error('结束时间不能小于开始时间'))
  } else {
    callback()
  }
}
const outsourceFeeInput = (val: any) => {
  ruleForm.value.outsourceFee = verifiyNumberInteger(val)
}
const rules = reactive<FormRules>({
  deviceId: [{ required: true, message: '请选择维修设备', trigger: 'change' }],
  failureCategoryId: [
    { required: true, message: '请选择故障类型', trigger: 'change' }
  ],
  failurePhenomenonId: [
    { required: true, message: '请选择故障现象', trigger: 'change' }
  ],
  solution: [{ required: true, message: '请输入解决方案', trigger: 'blur' }],
  description: [{ required: true, message: '请输入故障描述', trigger: 'blur' }],
  failureLevelId: [
    { required: true, message: '请选择故障等级', trigger: 'change' }
  ],
  repairFactory: [
    { required: true, message: '请选择维修厂家', trigger: 'change' }
  ],
  repairUserName: [
    { required: true, message: '请输入维修人员', trigger: 'blur' }
  ],
  outsourceFee: [
    { required: true, message: '请输入维修费用', trigger: 'blur' }
  ],
  content: [{ required: true, message: '请输入维修内容', trigger: 'blur' }],
  startTime: [
    { required: true, message: '请选择维修开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择维修结束时间', trigger: 'change' },
    { validator: validatorTime, trigger: 'change' }
  ],
  dealUserId: [{ required: true, message: '请选择审核人', trigger: 'change' }],
  verifyUserId: [{ required: true, message: '请选择验证人', trigger: 'change' }]
})
const failureLevels = ref<any>([])
const getFailureLevel = () => {
  dictionaryList({ configType: 'failure_level', keyword: '' }).then((res) => {
    if (res.code == 0) {
      failureLevels.value = res.data
    }
  })
}

const levelChange = (val: any) => {
  failureLevels.value.forEach((i: any) => {
    if (i.id == val) {
      ruleForm.value.failureLevel = i.configValue
    }
  })
}

//获取设备
const deviceList = ref<any>([])
const getDevice = () => {
  getDeviceListApi().then((res) => {
    if (res.code == 0) {
      deviceList.value = res.data
    }
  })
}
getDevice()

const deviceType = ref('')
const deviceChange = (val: any) => {
  if (val == '') {
    ruleForm.value.failureCategoryId = ''
    deviceType.value = ''
  } else {
    deviceList.value.forEach((i: any) => {
      if (i.id == val) {
        getFailureList(i.deviceType)
        deviceType.value = i.deviceType
      }
    })
  }
}

//获取故障类型
const failureList = ref<any>([])
const failureCategory = ref<any>('')
const failureCategoryId = ref<any>('')
const getFailureList = (val: any) => {
  getFailureCategoryApi(val).then((res) => {
    if (res.code == 0) {
      failureList.value = res.data
      if (failureCategoryId.value != '') {
        failureList.value.forEach((element: any) => {
          if (failureCategoryId.value == element.id) {
            ruleForm.value.failureCategoryId = element.id
            ruleForm.value.failureCategory = element.failureName
            getFailurePhenomenon(ruleForm.value.failureCategoryId)
          }
        })
      }
    }
  })
}

const failureChange = (val: any) => {
  ruleForm.value.failurePhenomenonId = ''
  ruleForm.value.failurePhenomenon = ''
  ruleForm.value.solution = ''
  getFailurePhenomenon(val)
  failureList.value.forEach((i: any) => {
    if (i.id == val) {
      ruleForm.value.failureCategory = i.failureName
    }
  })
}

//获取故障现象
const phenomenonList = ref<any>([])
const failurePhenomenon = ref<any>('')
const failurePhenomenonId = ref<any>('')
const getFailurePhenomenon = (val: any) => {
  getFailurePhenomenonApi(val).then((res) => {
    if (res.code == 0) {
      phenomenonList.value = res.data
      if (failurePhenomenonId.value != '') {
        phenomenonList.value.forEach((element: any) => {
          if (failurePhenomenonId.value == element.id) {
            ruleForm.value.failurePhenomenonId = element.id
            ruleForm.value.failurePhenomenon = element.failureName
          }
        })
        failurePhenomenonId.value = ''
        failurePhenomenon.value = ''
      }
    }
  })
}

const phenomenonChange = (val: any) => {
  phenomenonList.value.forEach((item: any) => {
    if (item.id == val) {
      ruleForm.value.solution = item.solution
      ruleForm.value.failurePhenomenon = item.failureName
    }
  })
}

//添加厂家
const gyOptions = ref<any>([])
const dialogVisible = ref<boolean>(false) //弹窗是否出现
const dialogForm = ref({
  width: '25%',
  title: ''
})
const addSupplier = () => {
  dialogForm.value.title = '添加厂家'
  dialogVisible.value = !dialogVisible.value
}
const cancelSupplier = () => {
  dialogVisible.value = !dialogVisible.value
}
const submitSupplier = () => {
  dialogVisible.value = !dialogVisible.value
  getPurveyor()
}
const getPurveyor = () => {
  getPurveyorList().then((res: any) => {
    if (res.code == 0) {
      gyOptions.value = res.data
    }
  })
}
getPurveyor()
const spareDialog = ref(false)
const spareType = ref('')
const orderNum = ref('')
//添加备件
const addSpare = () => {
  if (ruleForm.value.deviceId == '') {
    ElMessage.warning('请先选择维修设备')
  } else {
    spareType.value = deviceType.value
    spareDialog.value = !spareDialog.value
  }
}
//提交申请
const submitApply = () => {
  if (ruleForm.value.dealUserId == '') {
    ElMessage.warning('请选择备件审核人')
  } else {
    let params = {
      orderNum: id.value != '' ? id.value : orderNum.value,
      deviceId: ruleForm.value.deviceId,
      partApplyDetails: tableData.value,
      approveStatus: 1,
      dealUser: ruleForm.value.dealUserId,
      dealUserName: ruleForm.value.dealUserName
    }
    addRepairPartApplyApi(params).then((res) => {
      if (res.code == 0) {
        tableData.value = res.data.partUsageResponse
        orderNum.value = res.data.orderNum
        ruleForm.value.repairOrderNum = res.data.orderNum
        ElMessage.success('已提交审核')
      }
    })
  }
}

const deletePart = (id: any) => {
  deletePartApplyDetailApi(id).then((res) => {
    if (res.code == 0) {
      tableData.value = res.data
      ElMessage.success('删除成功')
    }
  })
}

//选择审核人
const dealUserChange = (val: any) => {
  shOptions.value.forEach((i: any) => {
    if (i.id == val) {
      ruleForm.value.dealUserName = i.realName
    }
  })
}

//获取审核人下拉
const shOptions = ref<any>([])
const shPeople = () => {
  getDirectorListApi(5).then((res) => {
    if (res.code == 0) {
      shOptions.value = res.data
    }
  })
}
shPeople()
//验证人下拉
const yzOptions = ref<any>([])
const yzPeople = () => {
  getDirectorListApi(2).then((res) => {
    if (res.code == 0) {
      yzOptions.value = res.data
    }
  })
}
yzPeople()

const verifyUserChange = (val: any) => {
  yzOptions.value.forEach((i: any) => {
    if (i.id == val) {
      ruleForm.value.verifyUserName = i.realName
    }
  })
}

const saCancel = () => {
  spareDialog.value = !spareDialog.value
}

const saSubmit = (val: any) => {
  let params = {
    orderNum: id.value != '' ? id.value : orderNum.value,
    deviceId: ruleForm.value.deviceId,
    partApplyDetails: val,
    approveStatus: 0
  }
  addRepairPartApplyApi(params).then((res) => {
    if (res.code == 0) {
      tableData.value = res.data.partUsageResponse
      orderNum.value = res.data.orderNum
      ruleForm.value.repairOrderNum = res.data.orderNum
      spareDialog.value = !spareDialog.value
    }
  })
}

//图片上传
const userInfo = Session.get('token')
const token = userInfo ? userInfo : ''
const headers = ref({
  'Content-Type': 'multipart/form-data',
  'Api-User-Token': token
})
let uploadLoading = ref([false, false, false])
const fileList = ref<UploadUserFile[]>([])
const filePictrue = ref<any>([])
const filePictrueList = ref<any>([])
const fileVedioList = ref<any>([])
// const fileList2 = ref<UploadUserFile[]>([])
const fileList3 = ref<UploadUserFile[]>([])
const handleUpload = (file: any, type: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '上传中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  uploadFileApi({ type: 15, file: file.file }).then((res) => {
    filePictrue.value.push(res.data.fileIds[0])
    if (
      res.data.fileIds[0].substring(
        res.data.fileIds[0].indexOf('?') - 3,
        res.data.fileIds[0].indexOf('?')
      ) == 'jpg' ||
      res.data.fileIds[0].substring(
        res.data.fileIds[0].indexOf('?') - 3,
        res.data.fileIds[0].indexOf('?')
      ) == 'png' ||
      res.data.fileIds[0].substring(
        res.data.fileIds[0].indexOf('?') - 3,
        res.data.fileIds[0].indexOf('?')
      ) == 'peg'
    ) {
      filePictrueList.value.push(res.data.fileIds[0])
      ElMessage.success('图片上传成功！')
    } else {
      fileVedioList.value.push(res.data.fileIds[0])
      ElMessage.success('视频上传成功！')
    }
    uploadLoading.value[type] = false
    loading.close()
  })
}

const appendixList = ref<any>([[], [], []])
const handleUpload3 = (file: any, type: any) => {
  const loading = ElLoading.service({
    lock: true,
    text: '上传中',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  uploadFileApi({ type: 15, file: file.file }).then((res) => {
    appendixList.value[0].push(res.data.fileIds[0])
    appendixList.value[1].push(res.data.fileNames[0])
    appendixList.value[2].push(res.data.fileSizes[0])
    uploadLoading.value[type] = false
    ElMessage.success('附件上传成功！')
    loading.close()
  })
}

const fileError = (err: any, type: any) => {
  ElMessage.error('项目文件上传失败！')
  fileList.value = []
  uploadLoading.value[type] = false
}
const fileBeforeUpload = (rawFile: any, type: any) => {
  if (filePictrueList.value.length == 9) {
    ElMessage.warning('已达最大上传限制')
    return false
  }
  uploadLoading.value[type] = true
  return true
}
const fileBeforeUpload2 = (rawFile: any, type: any) => {
  if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('上传附件大小不得超过10MB!')
    return false
  }
  return true
}

const fileExceedUpload = () => {
  ElMessage.warning('只能上传9张图片或视频')
}
const fileExceedUpload2 = () => {
  ElMessage.warning('只能上传10个附件')
}

const uploadRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  // let index = filePictrue.value.indexOf(uploadFile.url)
  // fileList.value.splice(index, 1)
  // filePictrue.value.splice(index, 1)
}
const uploadRemove3 = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  let index = fileList3.value.indexOf(uploadFile)
  appendixList.value[0].splice(index, 1)
  appendixList.value[1].splice(index, 1)
  appendixList.value[2].splice(index, 1)
}

const deletePic = (val: any, index: any, type: any) => {
  if (type == 1) {
    filePictrueList.value.splice(index, 1)
  } else {
    fileVedioList.value.splice(index, 1)
  }
  filePictrue.value.forEach((item: any, i: any) => {
    if (item == val) {
      fileList.value.splice(i, 1)
    }
  })
  filePictrue.value = filePictrue.value.filter((item: any) => item != val)
  console.log(fileList.value)
}

const handleFullScreen = (e: any) => {
  launchFullscreen(e.target)
}

const launchFullscreen = (element: any) => {
  //此方法不可以在異步任務中執行，否則火狐無法全屏
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen()
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen()
  } else if (element.oRequestFullscreen) {
    element.oRequestFullscreen()
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen()
  } else {
    var docHtml = document.documentElement
    var docBody = document.body
    var videobox = element
    var cssText = 'width:100%;height:100%;overflow:hidden;'
    docHtml.style.cssText = cssText
    docBody.style.cssText = cssText
    videobox.style.cssText = cssText + ';' + 'margin:0px;padding:0px;'
    document.IsFullScreen = true
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.value.repairPictures = filePictrue.value.join(',')
      ruleForm.value.fileUrls = appendixList.value[0].join(',')
      ruleForm.value.fileNames = appendixList.value[1].join(',')
      ruleForm.value.fileSizes = appendixList.value[2].join(',')
      if (tableData.value.length != 0) {
        for (let index = 0; index < tableData.value.length; index++) {
          if (tableData.value[index].approveStatus == 1) {
            ElMessageBox.confirm('当前有备件申请待审核. 无法提交!', '提示', {
              // confirmButtonText: '确认',
              cancelButtonText: '知道了',
              showConfirmButton: false,
              type: 'warning'
            })
            return
          }
        }
        for (let index = 0; index < tableData.value.length; index++) {
          if (tableData.value[index].approveStatus == 0) {
            ElMessageBox.confirm(
              '有备件待提交申请. 确认提交验证信息?',
              '提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
              .then(() => {
                tijiao()
                return
              })
              .catch(() => {
                ElMessage({
                  type: 'info',
                  message: '已取消'
                })
              })
            return
          }
        }
        tijiao()
      } else {
        tijiao()
      }
    } else {
      ElMessage.warning('当前有必填项未填写，无法提交')
    }
  })
}

const tijiao = () => {
  if (id.value == '') {
    if (change.value) {
      Reflect.set(ruleForm.value, 'repairId', wxId.value)
    }
    ruleForm.value.repairStatus = '3'
    addOutsourceRepairApi(ruleForm.value).then((res) => {
      if (res.code == 0) {
        ElMessage.success('添加成功')
        router.push({
          name: 'repairOrder'
        })
      }
    })
  } else {
    Reflect.set(ruleForm.value, 'id', wxId.value)
    submitVerifyApi(ruleForm.value).then((res) => {
      if (res.code == 0) {
        ElMessage.success('已提交验证')
        router.push({
          name: 'repairOrder'
        })
      }
    })
  }
}

//保存当前
const resetForm = async (formEl: FormInstance | undefined, where: any) => {
  ruleForm.value.repairStatus = '2'
  ruleForm.value.repairPictures = filePictrue.value.join(',')
  ruleForm.value.fileUrls = appendixList.value[0].join(',')
  ruleForm.value.fileNames = appendixList.value[1].join(',')
  ruleForm.value.fileSizes = appendixList.value[2].join(',')
  if (id.value == '') {
    Reflect.set(ruleForm.value, 'repairOrderNum', orderNum.value)
    if (change.value) {
      Reflect.set(ruleForm.value, 'repairId', wxId.value)
    }
    addOutsourceRepairApi(ruleForm.value).then((res) => {
      if (res.code == 0) {
        ElMessage.success('保存成功')
        router.push({
          name: where
        })
      }
    })
  } else {
    if (change.value != '' && change.value != undefined) {
      addOutsourceRepairApi(ruleForm.value).then((res) => {
        if (res.code == 0) {
          ElMessage.success('添加成功')
          router.push({
            name: where
          })
        }
      })
    } else {
      Reflect.set(ruleForm.value, 'id', wxId.value)
      Reflect.set(ruleForm.value, 'repairOrderNum', id.value)
      updateRepairApi(ruleForm.value).then((res) => {
        if (res.code == 0) {
          ElMessage.success('保存成功')
          router.push({
            name: where
          })
        }
      })
    }
  }
}

onMounted(() => {
  getFailureLevel()
  if (id.value != '') {
    repairDetailByOrderNumApi(id.value).then((res) => {
      if (res.code == 0) {
        ruleForm.value.deviceId = res.data.deviceId
        deviceChange(ruleForm.value.deviceId)
        failureCategoryId.value = res.data.failureCategoryId
        failureCategory.value = res.data.failureCategory
        failurePhenomenonId.value = res.data.failurePhenomenonId
        failurePhenomenon.value = res.data.failurePhenomenon
        ruleForm.value.solution = res.data.solution
        ruleForm.value.failureLevelId = res.data.failureLevelId
        ruleForm.value.failureLevel = res.data.failureLevel
        ruleForm.value.description = res.data.description
        ruleForm.value.repairFactory = res.data.repairFactory
        ruleForm.value.repairUserName = res.data.repairUserName
        ruleForm.value.outsourceFee = res.data.outsourceFee
        ruleForm.value.content = res.data.content
        ruleForm.value.startTime = res.data.startTime
        ruleForm.value.endTime = res.data.endTime
        ruleForm.value.dealUserName = res.data.dealUserName
        ruleForm.value.dealUserId = res.data.dealUser
        ruleForm.value.source = res.data.source
        if (!change.value) {
          tableData.value = res.data.partList
        }
        ruleForm.value.repairPictures = res.data.repairPictures
        if (res.data.repairPictures != '') {
          filePictrue.value = ruleForm.value.repairPictures.split(',')
          filePictrue.value.forEach((item: any) => {
            let obj = {
              url: item //后端反我的是半截地址，我自己需要拼接前面的部分
            }
            fileList.value.push(obj)
            let a = item.lastIndexOf('\?')
            let str = item.substring(a - 3, a)
            if (str == 'png' || str == 'jpg' || str == 'peg') {
              filePictrueList.value.push(item)
            } else {
              fileVedioList.value.push(item)
            }
          })
        }
        if (res.data.fileUrls != '') {
          appendixList.value[0] = res.data.fileUrls.split(',')
          appendixList.value[1] = res.data.fileNames.split(',')
          appendixList.value[2] = res.data.fileSizes.split(',')
          appendixList.value[0].forEach((item: any, idx: any) => {
            let o = {
              url: appendixList.value[0][idx],
              name: appendixList.value[1][idx]
            }
            fileList3.value.push(o)
          })
        }
        ruleForm.value.verifyUserId = res.data.verifyUserId
        ruleForm.value.verifyUserName = res.data.verifyUserName
      }
    })
    if (change.value == 'change') {
      id.value = ''
      orderNum.value = ''
    }
  }
})

const goSetting = () => {
  ElMessageBox.confirm('是否保存当前内容并去设置?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      resetForm(ruleFormRef.value, 'repairFaultItem')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}
</script>
<style scoped lang="scss">
.subandentry {
  font-size: var(--el-font-size-base);

  .back {
    cursor: pointer;
    color: rgba(140, 140, 140, 1);
    margin-bottom: 10px;
  }

  .title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 8px;
  }

  .row {
    margin-bottom: 20px;

    .el-form-item {
      margin-right: 10px;
    }
  }
}

.upload-demo {
  width: 50%;
}

.avatar-uploader .avatar {
  width: 84px;
  height: 84px;
  display: block;
}
</style>
<style>
.el-dialog__title {
  font-size: 20px !important;
  font-weight: 700 !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload--picture-card {
  width: 84px;
  height: 84px;
}

.avatar-uploader .el-upload-list--picture-card .el-upload-list__item {
  width: 84px;
  height: 84px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.picture {
  font-size: 14px;
  line-height: 84px;
  color: #8c939d;
  width: 84px;
  height: 84px;
  text-align: center;
}

.tips {
  font-size: 13px;
  font-weight: 400;
  line-height: 21px;
  color: rgba(140, 140, 140, 1);
}
.sets {
  cursor: pointer;
  color: var(--el-color-primary);
  margin-left: 5px;
}

.subandentry .el-upload-list__item {
  width: 100% !important;
  height: auto !important;
}
</style>
